package me.liuhui.mall.manager.service.security;

import me.liuhui.mall.manager.runtime.AdminSessionHolder;
import me.liuhui.mall.manager.service.PermissionService;
import me.liuhui.mall.manager.service.RoleService;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class AdminPermissionFilter extends OncePerRequestFilter {

    @Resource
    private PermissionService permissionService;
    @Resource
    private RoleService roleService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if (!request.getRequestURI().startsWith("/api")) {
            filterChain.doFilter(request, response);
            return;
        }
        CurrentAdmin currentAdmin = AdminSessionHolder.getCurrentAdmin();
        if (currentAdmin == null) {
            filterChain.doFilter(request, response);
            return;
        }
        currentAdmin.setPermissions(permissionService.currentPermissions());
        currentAdmin.setRoles(roleService.currentRoles());
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(currentAdmin, "N/A", currentAdmin.getAuthorities());
        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        //设置为已登录
        SecurityContextHolder.getContext().setAuthentication(authentication);
        filterChain.doFilter(request, response);
    }
}
